<script setup lang="ts">
import { reactive,ref, computed, watch, onUnmounted } from 'vue'
import { articleLists, articleRemove, articleWithdraw } from "../api/article"
import { Modal } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { createVNode } from 'vue';

type Key = string | number;

const props:any = defineProps({
    activeKey: String
})

const title = ref<string>('批量删除')
const state = reactive<{
  selectedRowKeys: Key[];
  selectedRows: Key[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  selectedRows: [],
  loading: false,
});
const current = ref<number>(1); // 页数
const pageSize = ref<number>(10); // 条数
const total = ref<number>(0); // 总数
const loading = ref<Boolean>(true) ; // 加载
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
}));
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
const columns = [
  // {
  //   name: 'Name',
  //   title: '关联账号',
  //   dataIndex: 'name',
  //   key: 'name',
  // },
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true
  },
  {
    title: '封面图',
    dataIndex: 'vertical_cover',
    key: 'vertical_cover',
    
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status',
  },
  {
    title: '状态原因',
    key: 'audit_msg',
    dataIndex: 'audit_msg',
    ellipsis: true, // 启用省略号配置对象，而非直接启用省略号。
  },
  {
    title: '阅读量',
    key: 'read_amount',
    dataIndex: 'read_amount',
  },
  {
    title: '发布时间',
    key: 'publish_time',
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
  }
];
const articleList:any = ref([]);

// 删除列表
const timer = ref()
const timer3 = ref()
const timer4 = ref()
const timer5 = ref()
const onDeleteList = () => {
  clearTimeout(timer.value)
  timer.value = null
  loading.value = true
  // const executeNexts = (index) => {
    let obj = {
        currentPage: current.value,
        pageSize: pageSize.value,
        search: '',
        type: 'news',
        collection: '',
        clearBeforeFetch: false
    }
    articleLists(obj).then((response:any) => {
      const result = response.data.data
      loading.value = false
      let arr = result.list.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != ''))
      // let arr2 = result.list.filter((item2:any) => item2['status'] != 'rejected' && item2.audit_msg == '')
      articleList.value = result.list
      console.log(arr)
      // 自动删除审核未通过的文章
      if(arr.length > 0) {
          const executeNext2 = (index) => {
            if(index >= arr.length) {
              console.log('45645645656456546')
              clearTimeout(timer3.value)
              timer3.value = null
              onDeleteList() // 调用删除列表
              return
            }
            if(arr[index]['status'] == 'publish') {
              // 状态已发布-先撤回再删除
              articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                  const result = response.data
                  console.log('articleRemove',result)
                  articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                      console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                      timer3.value =  setTimeout(() => {
                        executeNext2(index+1)
                      }, 2000)
                  }).catch(() => {
                  });
              }).catch(() => {
              });
            } else {
              articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                  console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                  timer3.value =  setTimeout(() => {
                    executeNext2(index+1)
                  }, 2000)
              }).catch(() => {

              });
            }
          }
          executeNext2(0)
      } else {
        // timer.value =  setTimeout(() => {
        //   executeNexts(index + 1)
        // }, 2000)
      }
      total.value = result.page.totalCount
    }).catch(() => {
      loading.value = false
    })
  // }
  // executeNexts(0)
}
// 删除按钮
const start = () => {
   Modal.confirm({
        title: '提示',
        icon: '',
        content: createVNode('div', { style: 'color:black;' }, '您删除的内容无法恢复，确认删除？'),
        okText: '确认',
        cancelText: '取消',
        onOk() {
            let arr = state.selectedRows.every((item2:any) => item2['status'] != 'publish')
            let arr2 = state.selectedRows.every((item2:any) => item2['status'] == 'publish' || item2['status'] == 'forbidden')
            if(arr) {
                // for(let i in state.selectedRowKeys) {
                     articleRemoveApi(state.selectedRowKeys) // 调用百家号删除接口
                // }
            } else if(arr2) {
                // for(let i in state.selectedRowKeys) {
                    articleWithdrawApi(state.selectedRowKeys) // 调用百家号撤回接口
                // }
            } else {
                message.warning('请选择相同的状态进行删除');
            }
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
    });
}

// 获取表格选择框勾选的数据
const onSelectChange = (selectedRowKeys: Key[], selectedRows: Key[]) => {
//   console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  state.selectedRowKeys = selectedRowKeys;
  state.selectedRows = selectedRows
};
// 分页选项
const handleTableChange = (
  pag: { pageSize: number; current: number },
  filters: any,
  sorter: any,
) => {
  console.log(pag,filters,sorter)
  clearTimeout(timer.value)
  timer.value = null
  current.value = pag.current
  pageSize.value = pag.pageSize
  onDeleteList() // 删除列表
};

watch(() => props.activeKey, (newVal:any) => {
    if(newVal == 2) {
        onDeleteList() // 删除列表
    }
})

// 撤回
const onWithdraw = (val:any) => {
    Modal.confirm({
        title: '提示',
        icon: '',
        content: createVNode('div', { style: 'color:black;' }, '您撤回的内容无法恢复，确认撤回？'),
        okText: '确认',
        cancelText: '取消',
        onOk() {
          let arr:any = []
          arr.push(val.article_id)
          articleWithdrawApi(arr) // 调用百家号撤回接口
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
}

// 调用百家号撤回接口
const articleWithdrawApi = (array:any) => {
  const executeNext4 = (index) => {
    if(index >= array.length) {
      clearTimeout(timer5.value)
      timer5.value = null
      return
    }
    articleWithdraw({article_id: array[index]}).then((response:any) => {
        const result = response.data
        console.log('articleRemove',result)
        let arr:any = []
        arr.push(array[index])
        articleRemoveApi(arr) // // 调用百家号删除接口
        timer5.value =  setTimeout(() => {
          executeNext4(index+1)
        }, 3000)
    }).catch(() => {
      state.loading = false;
      state.selectedRowKeys = [];
      state.selectedRows = []
    });
  }
  executeNext4(0)
}

// 删除
const onDelete = (val:any) => {
    Modal.confirm({
        title: '提示',
        icon: '',
        content: createVNode('div', { style: 'color:black;' }, '您删除的内容无法恢复，确认删除？'),
        okText: '确认',
        cancelText: '取消',
        onOk() {
          let arr:any = []
          arr.push(val.article_id)
          articleRemoveApi(arr) // 调用百家号删除接口
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
    });
}
// 调用百家号删除接口
const articleRemoveApi = (array: any) => {
  const executeNext3 = (index) => {
    if(index >= array.length) {
      clearTimeout(timer4.value)
      timer4.value = null
      state.loading = false;
      state.selectedRowKeys = [];
      state.selectedRows = []
      onDeleteList() // 调用删除列表
      return
    }
    articleRemove({article_id: array[index]}).then((response:any) => {
        const result = response.data
        console.log('articleRemove',result)
        message.success('删除成功');
        timer4.value =  setTimeout(() => {
            executeNext3(index+1)
        }, 1000)
    }).catch(() => {
      state.loading = false;
      state.selectedRowKeys = [];
      state.selectedRows = []
    });
  }
  executeNext3(0)
}

//离开界面
onUnmounted(() => {
    // 每次离开当前界面时，清除定时器
    clearTimeout(timer.value)
    clearTimeout(timer3.value)
    timer.value = null
    timer3.value = null
})
</script>
<template>
  <div class="deleteList">
    <div style="margin-bottom: 16px;text-align: right;">
      <a-button type="primary" :disabled="!hasSelected" :loading="state.loading" @click="start">
        {{ title }}
      </a-button>
    </div>
    <a-table :rowKey="(record:any) => record.article_id" :pagination="pagination" :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" :columns="columns" :data-source="articleList"  :loading="loading" @change="handleTableChange">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'title'">
              <a-tooltip :title="record.title">
                <div>
                   {{ record.title ? record.title : '' }}
                </div>
              </a-tooltip>
            </template>
            <template v-else-if="column.key === 'vertical_cover'">
                <div v-if="record.vertical_cover">
                    <img :src="record.vertical_cover" class="vertical_cover" alt="">
                </div>
                <div v-else>--</div>
            </template>
            <template v-else-if="column.key === 'status'">
               <div>
                  <a-tag v-if="record.status == 'publish'" color="success">已发布</a-tag>
                  <a-tag v-else-if="record.status == 'rejected'" color="error">审核未通过</a-tag>
                  <a-tag v-else-if="record.status == 'draft'" color="purple">草稿</a-tag>
                  <div v-else>--</div>
               </div>
            </template>
            <template v-else-if="column.key === 'audit_msg'">
                <div v-if="record.audit_msg">
                  <a-tooltip :title="record.audit_msg">
                    <div v-html="record.audit_msg" :style="{color: record.audit_msg_color}"></div>
                  </a-tooltip>
                </div>
                <div v-else>--</div>
            </template>
            <template v-else-if="column.key === 'read_amount'">
                <div v-if="record.audit_msg">
                  {{ record.read_amount }}
                </div>
                <div v-else>--</div>
            </template>
            <template v-else-if="column.key === 'publish_time'">
                <div>
                {{ record.publish_time ? record.publish_time : '' }}
                </div>
            </template>
            <template v-else-if="column.key === 'action'">
                <span v-if="record.status == 'publish'">
                   <a @click="onWithdraw(record)">撤回</a>
                </span>
                <span v-else>
                   <a @click="onDelete(record)">删除</a>
                </span>
            </template>
        </template>
    </a-table>
  </div>
</template>

<style scoped>
.vertical_cover{
    width: 100px;
    height: 60px;
    object-fit: cover;
}
</style>
